<template>
  <GridPage title="资料设置">
    <n-flex class="flex mt-12" vertical>
      <n-card title="个人信息😀">
        <n-grid :cols="10">
          <n-gi :span="9">
            <n-flex class="min-w-450">
              <n-avatar lazy :src="userStore.avatar_url" :size="100" round />
              <n-flex vertical>
                <n-flex>
                  <h2>{{ info.name }}</h2>
                  <h2 v-if="hasTitle">· {{ info.title }}</h2>
                </n-flex>
                <div class="text-16">
                  <n-text class="mr-10">UID:</n-text>
                  <n-text underline>#{{ userStore.user_id }}</n-text>
                </div>
                <InfoItem icon="i-fe:phone" :value="info.phone_number"></InfoItem>
                <InfoItem icon="i-fe:mail" :value="info.email"></InfoItem>
              </n-flex>
            </n-flex>
          </n-gi>
          <n-gi :span="1">
            <n-button text type="primary" @click="handle">编辑信息</n-button>
          </n-gi>
        </n-grid>
      </n-card>
      <n-card title="修改密码🔒">
        <n-grid :cols="8">
          <n-gi />
          <n-gi :span="6">
            <n-form
              ref="PasswordFormRef"
              :model="passwordForm"
              :rules="passwordRules"
              label-placement="left"
              label-width="auto"
            >
              <n-form-item path="originPsw" label="原密码">
                <n-input type="password" v-model:value="passwordForm.originPsw"></n-input>
              </n-form-item>
              <n-form-item path="newPsw" label="新密码">
                <n-input type="password" v-model:value="passwordForm.newPsw"></n-input>
              </n-form-item>
              <n-form-item path="newRepetPsw" label="重复新密码">
                <n-input type="password" v-model:value="passwordForm.newRepetPsw"></n-input>
              </n-form-item>
            </n-form>
            <n-flex justify="end">
              <n-button type="primary" @click="handleEditPassword">修改密码</n-button>
            </n-flex>
          </n-gi>
          <n-gi />
        </n-grid>
      </n-card>
    </n-flex>
  </GridPage>

  <MeModal ref="editInfoRef" title="编辑信息" width="600px" @ok="handleEditSave()">
    <n-form ref="infoFormRef" :model="infoForm" :rules="rules">
      <n-grid :cols="24" :x-gap="24">
        <n-form-item-gi label="姓名" path="name" :span="12">
          <n-input v-model:value="infoForm.name" maxlength="10" />
        </n-form-item-gi>
        <n-form-item-gi label="手机号码" path="phone_number" :span="12">
          <n-input v-model:value="infoForm.phone_number" maxlength="20" />
        </n-form-item-gi>
        <n-form-item-gi label="邮箱" path="email" :span="12">
          <n-input v-model:value="infoForm.email" maxlength="30" />
        </n-form-item-gi>
        <n-form-item-gi v-if="role === 'seeker'" label="我的身份" path="identity" :span="12">
          <n-select v-model:value="infoForm.identity" :options="identities" />
        </n-form-item-gi>
        <n-form-item-gi v-if="role === 'seeker'" label="当前状态" path="state" :span="12">
          <n-select v-model:value="infoForm.state" :options="states" />
        </n-form-item-gi>
        <n-form-item-gi v-if="role === 'seeker'" label="现居地" path="address_code" :span="12">
          <n-cascader
            v-model:value="infoForm.address_code"
            expand-trigger="hover"
            :options="cities"
            :show-path="true"
            check-strategy="child"
          />
        </n-form-item-gi>

        <n-form-item-gi label="性别" path="gender" :span="12">
          <n-radio-group v-model:value="infoForm.gender">
            <n-radio-button
              v-for="gender in genders"
              :key="gender.value"
              :value="gender.value"
              :label="gender.label"
            />
          </n-radio-group>
        </n-form-item-gi>

        <n-form-item-gi v-if="role === 'seeker'" label="出生年月" path="birth_date" :span="12">
          <n-date-picker
            v-model:formatted-value="infoForm.birth_date"
            type="month"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="y年 M月"
            year-format="y年"
            month-format="M月"
          />
        </n-form-item-gi>
      </n-grid>
    </n-form>
  </MeModal>
</template>

<script setup>
import { MeModal, GridPage, InfoItem } from '@/components'
import { useForm, useModal } from '@/composables'
import {
  useAuthStore,
  useRecruiterStore,
  useSeekerStore,
  useAdminStore,
  useUserStore,
} from '@/store'
import { cities } from '@/data'
import seekerApi from '@/api/seeker'
import recruiterApi from '@/api/recruiter'
import adminApi from '@/api/admin'
import userApi from '@/api/user'
const userStore = useUserStore()
const router = useRouter()

const info = ref({})
const role = ref()

const genders = [
  { value: 0, label: '女' },
  { value: 1, label: '男' },
]

const identities = [
  { value: 0, label: '学生' },
  { value: 1, label: '职场人' },
]

const states = [
  { value: 0, label: '离校，正在找工作' },
  { value: 1, label: '在校，可即刻到岗' },
  { value: 2, label: '在校，看看机会' },
  { value: 3, label: '在校，暂时不找工作' },
]

const [editInfoRef] = useModal()
const [infoFormRef, infoForm, infoValidation] = useForm({})

const rules = {
  name: { required: true, message: '此为必填项', trigger: ['blur', 'change'] },
  phone_number: { required: true, message: '此为必填项', trigger: ['blur', 'change'] },
  email: { required: true, message: '此为必填项', trigger: ['blur', 'change'] },
  gender: { type: 'number', required: true, message: '此为必填项', trigger: ['blur'] },
}

const passwordRules = {
  originPsw: { required: true, message: '此为必填项', trigger: ['blur', 'change'] },
  newPsw: { required: true, message: '此为必填项', trigger: ['blur', 'change'] },
  newRepetPsw: { required: true, message: '此为必填项', trigger: ['blur', 'change'] },
}

const hasTitle = ref(false)

function handle() {
  editInfoRef.value.open()
}

async function handleEditSave() {
  await infoValidation()
  let res
  if (role.value === 'recruiter') {
    res = await recruiterApi.updateRecruiter(infoForm.value)
  } else if (role.value === 'seeker') {
    res = await seekerApi.updateSeeker(infoForm.value)
  } else if (role.value === 'admin') {
    res = await adminApi.updateAdmin(infoForm.value)
  }
  if (res.data) {
    $message.success('个人信息设置成功')
    info.value = { ...infoForm.value }
    if (role.value === 'recruiter') {
      useRecruiterStore().recruiter.name = infoForm.value.name
    } else if (role.value === 'seeker') {
      useSeekerStore().seeker.name = infoForm.value.name
    } else if (role.value === 'admin') {
      useAdminStore().admin.name = infoForm.value.name
    }
    useAuthStore().setHasName(true)
  }
}

const PasswordFormRef = ref()
const passwordForm = ref({})
async function handleEditPassword() {
  await PasswordFormRef.value?.validate()
  const { newPsw, newRepetPsw } = passwordForm.value
  if (newPsw !== newRepetPsw) {
    return $message.error('两次密码输入不一致')
  }
  passwordForm.value.user_id = userStore.user_id
  const { data } = await userApi.updatePassword(passwordForm.value)
  //返回的data为token，保存至store
  if (data) {
    useAuthStore().setToken(data)
    $dialog.success({
      title: '密码修改成功',
      closable: false,
      maskClosable: false,
      positiveText: '确定',
      onPositiveClick() {
        router.go(0)
      },
    })
  }
}

onMounted(() => {
  role.value = userStore.role
  //设置是否显示头衔
  if (role.value !== 'recruiter') {
    hasTitle.value = false
  } else {
    hasTitle.value = useRecruiterStore().recruiter.title !== null
  }
  if (role.value === 'recruiter') {
    const recruiterStore = useRecruiterStore()
    info.value = recruiterStore.recruiter
    infoForm.value = { ...recruiterStore.recruiter }
  } else if (role.value === 'seeker') {
    const seekerStore = useSeekerStore()
    info.value = seekerStore.seeker
    infoForm.value = { ...seekerStore.seeker }
    rules.identity = { type: 'number', required: true, message: '此为必填项', trigger: ['blur'] }
    rules.state = { type: 'number', required: true, message: '此为必填项', trigger: ['blur'] }
    rules.address_code = { required: true, message: '此为必填项', trigger: ['blur'] }
    rules.birth_date = { required: true, message: '此为必填项', trigger: ['blur'] }
  } else if (role.value === 'admin') {
    const adminStore = useAdminStore()
    info.value = adminStore.admin
    infoForm.value = { ...adminStore.admin }
  }
  if (info.value.name === null) {
    $message.warning('请先完善个人资料')
    editInfoRef.value.open({
      closable: false,
      showCancel: false,
    })
  }
})
</script>
